<template>
  <div class="combined_tts">
    <div class="title">
      <h1>最自然的AI 语音</h1>
    </div>
    <div class="desc">
      <h3>文本转语音</h3>
    </div>
    <div class="text">
      <div class="box" contenteditable="true" @input="updateText"></div>
    </div>
    <div class="operation">
      <el-button @click="submitFile">开始转换</el-button>
      <!--      <el-button @click="downloadFile">下载</el-button>-->
      <el-upload
          :action="uploadUrl"
          accept=".wav,.mp3,.pcm"
          ref="upload"
          :data="uploadData"
          :auto-upload="false"
          :show-file-list="false"
          :on-success="success"
          :on-change="handleChange"
          :before-remove="handleRemove"
          :file-list="fileList"
          :limit="1">
        <el-button class="uploadMusic">上传背景音乐</el-button>
      </el-upload>
      <div class="file-list">
        <span v-for="file in fileList" :key="file.name" class="file-item">
            {{ file.name }}<i class="el-icon-close removeIcon" @click="removeFile(file)"></i>
        </span>
      </div>
    </div>
    <div class="footer">
      <audio
          class="audioPlay"
          ref="audioPlayer"
          :src="audioSrc"
          controls></audio>
      <div class="audio-controls">
        <!--        <el-input v-model="audioUrl" placeholder="输入音频 URL..."></el-input>-->
        <el-button type="primary" @click="fetchAudio">获取音频</el-button>
        <el-button type="danger" @click="pauseAudio">暂停</el-button>
        <el-button type="success" @click="stopAudio">停止</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import download_file from "@/store/download_file";
import axiosInstance from "@/store/apiClient";


export default {
  name: 'HomePage',
  data() {
    return {
      text: '',
      download_file_name: '',
      audioSrc: '',
      uploadUrl: 'http://127.0.0.1:8889/tts',
      fileList: []
    }
  },
  computed: {
    uploadData() {
      return {
        // 额外的文本数据
        text: this.text
      };
    }
  },
  methods: {
    updateText(event) {
      this.text = event.target.innerText; // 更新 data 中的 text
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    removeFile(file) {
      this.fileList = this.fileList.filter(f => f.uid !== file.uid);
    },
    success(response) {
      this.download_file_name = response['download_file_name']
      this.$notify.success({
        title: '成功',
        message: '转换成功',
      })
    },
    submitFile() {
      // 手动触发文件上传
      if (this.text.length <= 0) {
        this.$notify.error({
          title: '错误',
          message: '内容为空',
        })
        return
      }
      // 获取文件列表
      const fileList = this.$refs.upload.uploadFiles;
      // 判断是否有文件需要上传
      if (fileList.length > 0) {
        // 手动触发文件上传
        this.$refs.upload.submit();
      } else {
        let _data = {
          text: this.text
        }
        let config = {
          headers: {
            'Content-Type': 'application/json'
          }
        }
        axiosInstance.post('/tts', _data, config).then(response => {
          if (response.status === 200) {
            this.download_file_name = response.data.download_file_name
            this.$notify.success({
              title: '成功',
              message: '转换成功',
            })
          }else {
            this.$notify.error({
              title: '错误',
              message: `${response.data.msg}`,
            })
          }
        }).catch(error => {
          console.error('获取音频失败:', error);
        });

      }
    },
    downloadFile() {
      let _data = {
        file_name: this.download_file_name
      }
      download_file.get(_data)
    },
    fetchAudio() {
      // 使用 Axios 获取音频数据
      let params = {
        file_name: this.download_file_name
      }
      let url = '/download?' + Object.keys(params).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
          .join('&');
      axiosInstance.get(url, {responseType: 'blob'})
          .then(response => {
            // 创建一个 Blob 对象
            const blob = new Blob([response.data], {type: 'audio/mpeg'});
            // 创建一个 URL 对象
            this.audioSrc = URL.createObjectURL(blob);
          })
          .catch(error => {
            console.error('获取音频失败:', error);
          });
    },
    pauseAudio() {
      this.$refs.audioPlayer.pause(); // 暂停音频
    },
    stopAudio() {
      this.$refs.audioPlayer.pause(); // 暂停音频
      this.$refs.audioPlayer.currentTime = 0; // 重置播放时间
    }
  }
}
</script>


<style scoped>
.combined_tts {
  background-image: url('@/assets/backgruond.png'); /* 替换为你的图片路径 */
  background-size: cover; /* 使背景图片覆盖整个 div */
  background-position: center; /* 背景图片居中 */
  width: 100%; /* 设置宽度 */
  height: 100vh; /* 设置高度 */
  color: white; /* 文字颜色 */
  display: flex; /* 使内容居中 */
  justify-content: center; /* 水平居中 */
  flex-direction: column;
  align-items: center; /* 垂直居中 */
}

.title {
  width: 100%;
  display: flex; /* 使内容居中 */
  justify-content: center; /* 水平居中 */
}

.desc {
  display: flex; /* 使内容居中 */
  justify-content: center; /* 水平居中 */
  width: 100%;
}

.text {
  display: flex; /* 使内容居中 */
  justify-content: center; /* 水平居中 */
  width: 100%;
}

.box {
  border: 4px solid #7a0e9f; /* 边框 */
  border-radius: 15px; /* 圆角 */
  width: 600px;
  height: 260px;
  padding: 20px;
  color: aliceblue;
  background-color: #000000; /* 背景颜色 */
  cursor: text; /* 输入时显示文本光标 */
  overflow-y: auto; /* 当内容超出时显示垂直滚动条 */
  transition: background-color 0.3s; /* 悬停过渡效果 */
}

.box:focus {
  outline: none; /* 去掉聚焦时的默认边框 */
//background-color: #e0f7e0; /* 聚焦时改变背景颜色 */
}

.operation {
  margin-top: 10px;
  width: 648px;
  display: flex; /* 使内容居中 */
  justify-content: left;
}

.uploadMusic {
  margin-left: 10px;
}

.file-item {
  font-size: 14px;
  margin-left: 10px;
  height: 38px;
  display: flex; /* 使内容居中 */
  align-items: center;
}

.removeIcon {
  margin-left: 8px;
}

.removeIcon:hover {
  color: aqua;
  cursor: pointer;
}

.audioPlay {
  margin-right: 20px;
}

.audio-controls {
  display: flex; /* 使内容居中 */
  justify-content: left; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.footer {
  width: 648px;
  margin-top: 10px;
  display: flex; /* 使内容居中 */
  justify-content: left; /* 水平居中 */
}
</style>